package cn.eleven.service;

import cn.eleven.dao.LeaseDAO;
import cn.eleven.dao.RoomDAO;
import cn.eleven.dao.impl.LeaseDAOImpl;
import cn.eleven.dao.impl.RoomDAOImpl;
import cn.eleven.entity.Lease;
import cn.eleven.entity.Room;
import cn.eleven.util.DBUtil;

import java.sql.*;
import java.util.List;

/**
 * 1.开始一个事务
 * 2.执行一系列的数据库操作
 * 3.提交事务/回滚事务
 */
public class RoomService {
    private final RoomDAO roomDAO = new RoomDAOImpl();
    private final LeaseDAO leaseDAO = new LeaseDAOImpl();

    /**
     * 获取所有房间
     * @return 房间列表
     */
    public List<Room> getAllRooms() {
        Connection conn = null;
        try {
            conn = DBUtil.getConnection();
            return roomDAO.findAll(conn);
        } catch (SQLException e) {
            e.printStackTrace();
            return List.of();
        } finally {
            DBUtil.close(conn, null, null);
        }
    }

    /**
     * 预订房间，容量减1
     * @param roomId 房间ID
     * @param userId 用户ID
     * @return 是否成功
     */
    public boolean rentRoom(int roomId, int userId) {
        Connection conn = null;
        try {
            conn = DBUtil.getConnection();
            conn.setAutoCommit(false);
            // 获取房间信息
            Room room = roomDAO.findById(conn, roomId);
            if (room == null || !"AVAILABLE".equals(room.getStatus()) || room.getCapacity() <= 0) {
                return false;
            }
            // 更新房间容量
            room.setCapacity(room.getCapacity() - 1);
            if (room.getCapacity() == 0) {
                room.setStatus("OCCUPIED");
            }
            if (!roomDAO.update(conn, room)) {
                conn.rollback();
                return false;
            }
            // 创建租赁记录（假设 LeaseDAO 已实现）
            Lease lease = new Lease();
            lease.setUserId(userId);
            lease.setRoomId(roomId);
            lease.setStartTime(new Timestamp(System.currentTimeMillis()));
            if (leaseDAO.insert(conn, lease) <= 0) {
                conn.rollback();
                return false;
            }
            // 提交事务
            conn.commit();
            return true;
        } catch (SQLException e) {
            try {
                if (conn != null) conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
            return false;
        } finally {
            DBUtil.close(conn, null, null);
        }
    }

    /**
     * 退订房间，容量加1
     * @param roomId 房间ID
     * @param userId 用户ID
     * @return 是否成功
     */
    public boolean returnRoom(int roomId, int userId) {
        Connection conn = null;
        try {
            conn = DBUtil.getConnection();
            conn.setAutoCommit(false);
            // 获取房间信息
            Room room = roomDAO.findById(conn, roomId);
            if (room == null || "MAINTENANCE".equals(room.getStatus()) || "CLOSED".equals(room.getStatus())) {
                return false;
            }
            // 更新房间容量
            room.setCapacity(room.getCapacity() + 1);
            if (room.getCapacity() > 0) {
                room.setStatus("AVAILABLE");
            }
            if (!roomDAO.update(conn, room)) { // 判断是否执行异常，异常就回滚
                conn.rollback();
                return false;
            }
            // 更新租赁记录
            Lease lease = leaseDAO.findActiveLeaseByRoomId(conn, roomId);
            if (lease == null) {
                conn.rollback();
                return false;
            }
            lease.setEndTime(new Timestamp(System.currentTimeMillis()));
            if (leaseDAO.update(conn, lease) <= 0) {
                conn.rollback();
                return false;
            }
            // 提交事务
            conn.commit();
            return true;
        } catch (SQLException e) {
            try {
                if (conn != null) conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
            return false;
        } finally {
            DBUtil.close(conn, null, null);
        }
    }
    public int getRoomPrice(int roomId) throws SQLException {
        String sql = "SELECT price FROM room WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, roomId);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                return rs.getInt("price");
            }
        }
        return 0; // 如果查询失败，则返回 0
    }

}